package com.lumlord.common.spring;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lumlord.common.log.Log;
import com.lumlord.common.log.LogFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.lumlord.common.domain.Result;
import com.lumlord.common.exception.BusinessException;

/**
 * @author suntongxin Create on 2017年12月12日下午1:55:12 All right reserved
 */
@ControllerAdvice
@RestControllerAdvice
//@RestControllerAdvice(annotations = { RestController.class, Controller.class, ControllerRequestMapping.class })
public class PubExceptionHandler implements HandlerExceptionResolver {
    public Log log = new LogFactory(getClass());

    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    }

    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     */
    @ModelAttribute
    public void addAttributes(Model model) {
    }

    @ExceptionHandler(value = Exception.class)
    public Result handle(Exception e, HttpServletRequest request) {
        Integer code = getStatus(request).value();
        if (!(e instanceof BusinessException)) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
             e.printStackTrace(new PrintStream(baos));
            String exception = baos.toString();
            log.info(exception);
            return Result.exception(600, e.getMessage() + ":" + e.getClass());
        }
        if (404 == code) {
            return Result.exception(getStatus(request).value(), "no found api!");
        }
        return Result.exception(getStatus(request).value(), e.getMessage());

    }


    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {

        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
	        /* try {
	                  String errorMsg="";
	                  boolean isAjax= "1".equals(request.getParameter("isAjax"));
	                  
	                  //ex 为业务层抛出的自定义异常
	                  if(ex instanceof ServiceCustomException){
	                      ServiceCustomException customEx=    (ServiceCustomException)ex;
	                      
	                      errorMsg ="customStatus:"+customEx.getCustomStatus() +",customMessage:"+customEx.getCustomMessage()
	                              +"\r\n"+ ExceptionUtils.getStackTrace(customEx);
	                      logger.error(errorMsg);
	                  }else{
	                    //ex为非自定义异常，则
	                      errorMsg=ExceptionUtils.getStackTrace(ex);
	                      logger.error(errorMsg);
	                       
	                  }
	              
	                  if(isAjax){
	                        
	                      response.setContentType("application/json;charset=UTF-8");
	                       response.getWriter().write(JSON.toJSONString(AjaxUtil.messageMap(500, errorMsg)));
	                       return new   ModelAndView();
	                  }else{
	                      //否则，  输出错误信息到自定义的500.jsp页面
	                      ModelAndView mv = new ModelAndView("/error/500.jsp");
	                      mv.addObject("errorMsg", errorMsg);
	                      return mv ;
	                  }
	            } catch (IOException e) {
	                logger.error(ExceptionUtils.getStackTrace(e));
	            }*/
        return new ModelAndView();

    }


}